import axios from "axios";

const service = axios.create({
    responseType: "arraybuffer"
})

service.interceptors.request.use(config => {
    config.headers["Authorization"] = sessionStorage.getItem("token_login")
    return config;
},error => {
    console.log(error)
})

service.interceptors.response.use(success => {
    const headers = success.headers;
    let regExp = RegExp(/application\/json/);
    if (headers['content-type'].match(regExp)){
        success.data = unitToString(success.data)
    }else {
        console.log(123)
        let fileDownload = require('js-file-download');
        let fileName = headers['content-disposition'].split(';')[1].split('filename=')[1];
        let contentType = headers['content-type'];
        fileName = decodeURIComponent(fileName)
        fileDownload(success.data,fileName,contentType)
    }
},error => {
    console.log(error)
})

function unitToString(unitArray){
    let encodeString = String.fromCharCode().apply(null,new Uint8Array(unitArray));
    let decodeString = decodeURIComponent(escape(encodeString));
    return JSON.parse(decodeString)
}

let base = ''

export const downloadRequest= (url,params)=>{
    return service({
        method:"get",
        url:base+url,
        data:params
    })
}